<?php
/**
 * Created by JetBrains PhpStorm.
 * User: ZHOUYANG
 * Date: 13-3-30
 * Time: 下午2:37
 */

function loadModule($module, $params = array())
{
    global $_user, $_session;

    if ($params)
    {
        extract($params);
    }

    $content = '';
    if (file_exists($module_file = MODULE_PATH . $module . '.php'))
    {
        ob_start();
        include $module_file;
        $content = ob_get_contents();
        ob_end_clean();
    }
    return $content;
}

function module($module, $params = array(), $cache_name = '', $expire = -1)
{
    if (! $cache_name)
        $cache_name = $module;

    $content = '';
    if ($expire < 0)
    {
        // no cache need
        $content = loadModule($module, $params);
    }
    else
    {
        // need cache for expire time
        if (! ($content = cache('cache:' . $cache_name)))
        {
            // no cache or cache expire out
            $content = loadModule($module, $params);

            cache('cache:' . $cache_name, $content, $expire);
        }
    }
    return $content;
}

function site_url($var=NULL) {
    if($var==NULL){
        return SITE_URL;
    }else{
        $var = trim($var,'/');
        return SITE_URL.$var;
    }
}

function e($s){
    echo $s,'<br/>';
}

function return_ip()
{
   $ip = "-1";
   if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
   {
        $ip_a = explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']) ;
        for($i=0;$i<count($ip_a);$i++)
        {//
            $tmp = trim($ip_a[$i]) ;
            if($tmp=='unknown'||$tmp=='127.0.0.1'||strncmp($tmp,'10.',3)==0||strncmp($tmp,'172',3)==0||strncmp($tmp,'192',3)==0)
                continue ;
            $ip = $tmp;
            break ;
        }
   }
   else if(!empty($_SERVER['HTTP_CLIENT_IP']))
   {
        $ip = trim($_SERVER['HTTP_CLIENT_IP']);
   }
   else if (!empty($_SERVER['REMOTE_ADDR']))
   {
        $ip = trim($_SERVER['REMOTE_ADDR']);
   }
   else
   {
        $ip = "-1";
   }
   return $ip;
}

function p($info, $exit = true, $ret = false)
{
    if (defined('RUNNING_MODE') && RUNNING_MODE == 'dev')
    {
        $debug = debug_backtrace();

        $output = '';
        $output .= '<b>File</b>:' . $debug[0]['file'] . '<br/>';
        $output .= '<b>Line</b>:' . $debug[0]['line'] . '<br/>';
        $output .= '<b>Info</b>:<br/>';
        $output .= '<pre>';
        $output .= var_export($info, true);
        $output .= '</pre>';

        if ($ret)
            return $ret;
        else
            echo $output;
        if ($exit)
            exit;
    }
    else
    {
        return;
    }
}

function l($info, $file = 'info',$dir = LOG_PATH)
{
    $debug = debug_backtrace();
    if (count($debug) > 1)
        $debug = $debug[1];
    else
        $debug = $debug[0];

    $time = date('Y-m-d H:i:s');
    $ip = $_SERVER['REMOTE_ADDR'];
    $url = $_SERVER['REQUEST_URI'];
    $file_name = $debug['file'];
    $line = $debug['line'];
    $function = $debug['function'];
    $info = is_string($info) ? $info : var_export($info, true);

    $server_addr = $_SERVER['SERVER_ADDR'];

    $str = 'Time:' . $time . ', ' .
           'Server:' . $server_addr . ', ' .
           'IP:' . $ip . ', ' .
           'URL:' . $url . ', ' .
           'File:' . $file_name . ', ' .
           'Line:' . $line . ', ' .
           'Function:' . $function . ', ' .
           'Info:' . $info . "\n";
    file_put_contents($dir . $file . '.log', $str, FILE_APPEND);
}

function curUrlName($str)
{
    $cur_url_array = explode('.',$str);
    $cur_url_name = str_replace("/","",$cur_url_array[0]);
    return $cur_url_name;
}

//remove page val's url
//@caixudong 增加两个参数，第一个是手动传入的额外参数，第二个是否从URL删除分页参数，默认删除
function parse_cur_url($p = array(),$remove_page = true){

    //base url
    $base_name = '/' . basename($_SERVER['SCRIPT_FILENAME']);

    //ex url
//    $tmp_arr = $_GET + $_POST + $p;
    $tmp_arr = array_merge($_GET, $_POST, $p);
            // remove page
    if($remove_page) unset($tmp_arr['page']);
    if($tmp_arr)
        $ex_url = http_build_query($tmp_arr);
    else
        $ex_url = '';

    //full url
    if($ex_url)
        $full_url = $base_name."?".$ex_url;
    else
        $full_url = $base_name;

    return $full_url;
}
//截取中文字符
function cnSubStr($string,$sublen,$tip='')
{
    $len = strlen($string);
    if($sublen>=$len)
    {
        return $string;
    }
    $s="";
    for($i=0;$i<$sublen;$i++)
    {
        if(ord($string{$i})>127)
        {
            $s.=$string{$i}.$string{++$i};
            continue;
        }else{
            $s.=$string{$i};
            continue;
        }
    }

    if(strlen($s) >= $len)
        return $s;
    return $s.$tip;
}

//去除空格
function trim_space($s) {
	$s = mb_ereg_replace('^(　| )+', '', $s);
	$s = mb_ereg_replace('(　| )+$', '', $s);
	return $s;
}

//网页内容抓取 add by final
function curl_get_contents($url,$timeout = 5){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');
//    curl_setopt($ch, CURLOPT_REFERER,_REFERER_);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    @curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACH, true);
    curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 86400); // 缓存一天
    $content = curl_exec($ch);
    curl_close($ch);
    return $content;
}


// array_diff's bug for PHP5.2.6-5.3.3
function my_array_diff($a1, $a2)
{
    $a2 = array_flip((array)$a2);
    foreach ((array)$a1 as $key => $item)
    {
        if (isset($a2[$item]))
        {
            unset($a1[$key]);
        }
    }
    return $a1;
}

function d($info = null, $time = false)
{
    if (! DEBUG)
        return;
    static $debug_info = array();
    if ($info != 'get_debug_data')
    {
        $debug_info[] = array('info'=>$info, 'backtrace'=>debug_backtrace());
        if ($time)
            time_debug('debug_time_' . count($debug_info));
    }

    return $debug_info;
}

//去除空格判断空
function trim_empty($str,$is_zh = false){
    $str = $is_zh ? trim_space($str) : trim($str);
    return empty($str);
}
//获取HOST
function getHttpHost(){

    return "http://".(isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''));
}
//跳转
function redirect($uri = '/', $method = 'location', $http_response_code = 302)
{
    switch($method)
    {
        case 'refresh'	: header("Refresh:0;url=".$uri);
            break;
        default			: header("Location: ".$uri, TRUE, $http_response_code);
            break;
    }
    exit;
}

$pub_roles_configs = array(
    1=>array(2,3,10),
    2=>array(10),
    3=>array(4,10),
    4=>array(5,10),
    5=>array(6,10),
    6=>array(7,8,10),
    7=>array(4,10),
    8=>array(9,10),
    9=>array(),
    10=>array(),
);

function getPubStatusClass($funs,$status,$v,$test_is_role,$is_upload,$is_super_admin){
    global $pub_roles_configs,$_session;
    if($funs['status'] == $status){
        if($is_super_admin && $status == 9){
            $url = 'list.php?a=logstatus&fun_id='.$funs['fun_id'].'&status='.$status;
            echo '<li class="select"><a href="'.site_url($url).'" target="dialog" title="置为'.$v.'?">>再次发布</a></li>';
        }else{
            echo '<li class="select">'.$v.'</li>';
        }
    }else{
        if(in_array($status,$pub_roles_configs[$funs['status']])){
            $is_active = false;
            switch($status){
                case 1:
                case 2:
                case 3:
                case 5://仅负责人操作
                case 10:
                    $is_active = $funs['puser_id'] == $_session->get('user_id');
                break;
                case 4://所有人都提交，并且是负责人
                    $is_active = $is_upload && $funs['puser_id'] == $_session->get('user_id');
                break;
                case 6://是发布人和负责人
                    $is_active = in_array($_session->get('user_id'),array($funs['puser_id'],$funs['user_id']));
                break;
                case 7:
                case 8://是不是测试或者是超级管理员
                    $is_active = $test_is_role || $is_super_admin;
                break;
                case 9://只有负责人才可以发布，并且要时间大于填写的发布时间
                    $is_active = $funs['puser_id'] == $_session->get('user_id');
                break;
                    
            }

            if(!$is_active){
                $v = $funs['status'] == 7 ? '重新提交' : $v;
                echo '<li class="active">'.$v.'</li>';
            }else{
                if(in_array($status,array(2,7,10)) || ($status == 8 && !$test_is_role && $is_super_admin) || ($status == 9 && strtotime($funs['online_time']) > time())){
                    $url = 'list.php?a=logstatus&fun_id='.$funs['fun_id'].'&status='.$status;
                    echo '<li class="active"><a href="'.site_url($url).'" target="dialog" title="置为'.$v.'?">>'.$v.'</a></li>';
                }else{
                    echo '<li class="active"><a href="javascript:void(0);" onclick="setPubStatus(\''.$funs['fun_id'].'\',\''.$status.'\',\''.$v.'\')" title="置为'.$v.'?">>'.$v.'</a></li>';
                }
            }
        }else{
            echo '<li class="disabled">'.$v.'</li>';
        }
    }
    
    
}

function getPubStatusLog($status){
    global $pub_status_configs;
    return '将状态置为：'.$pub_status_configs[$status];
}

function rtxMessage($messages){
    foreach($messages as $v){
        $title = iconv('UTF-8','GBK',$v['title']);
        $message = iconv('UTF-8','GBK',$v['message']);
        $user_name = iconv('UTF-8','GBK',$v['user_name']);
        $rtx_notice = 'http://180.168.84.109:8012/sendnotify.cgi?delaytime=0&title='.$title.'&msg='.$message.'&receiver='.$user_name;
        //异步调用
//        $fp = fsockopen("180.168.84.109", 8012, $errno, $errstr, 30);
//        if (!$fp) {
//            echo "$errstr ($errno)<br />\n";
//        } else {
//            $out = "GET /sendnotify.cgi?delaytime=0&title=$title&msg=$message&receiver=$user_name / HTTP/1.1\r\n";
//            $out .= "Host: 180.168.84.109\r\n";
//            $out .= "Connection: Close\r\n\r\n";
//
//            fwrite($fp, $out);
//            /*忽略执行结果
//            while (!feof($fp)) {
//            echo fgets($fp, 128);
//            }*/
//            fclose($fp);
//        }
        curl_get_contents($rtx_notice,10);
    }
}


function getMultipleDocuments($nodes, $referer){
    set_time_limit(90);
    if(!$referer){
        $referer = $nodes[0];
    }
    $node_count = count($nodes);

    $curl_arr = array();
    $master = curl_multi_init();

    for($i = 0; $i < $node_count; $i++)
    {
        $curl_arr[$i] = curl_init($nodes[$i]);
        curl_setopt($curl_arr[$i], CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl_arr[$i],CURLOPT_FRESH_CONNECT,true);
        curl_setopt($curl_arr[$i],CURLOPT_CONNECTTIMEOUT,10);
        curl_setopt($curl_arr[$i],CURLOPT_RETURNTRANSFER,true);
        curl_setopt($curl_arr[$i],CURLOPT_REFERER,$referer);
        curl_setopt($curl_arr[$i],CURLOPT_TIMEOUT,30);

        curl_multi_add_handle($master, $curl_arr[$i]);
    }
    $previousActive = -1;
    $finalresult = array();
    $returnedOrder = array();
    do{
        curl_multi_exec($master, $running);
        if($running !== $previousActive){
            $info = curl_multi_info_read($master);
            if($info['handle']){
                $finalresult[] = curl_multi_getcontent($info['handle']);
                $returnedOrder[] = array_search($info['handle'], $curl_arr, true);
                curl_multi_remove_handle($master, $info['handle']);
                curl_close($curl_arr[end($returnedOrder)]);
                echo 'downloaded '.$nodes[end($returnedOrder)].'. We can process it further straight away, but for this example, we will not.';
                ob_flush();flush();
            }
        }
        $previousActive = $running;
    }while($running > 0);
    curl_multi_close($master);

    set_time_limit(30);
    return array_combine($returnedOrder, $finalresult);
}

//$nodes = array('http://127.0.0.1/test/sock_server.php','http://127.0.0.1/test/sock_server.php','http://127.0.0.1/test/sock_server.php','http://127.0.0.1/test/sock_server.php','http://127.0.0.1/test/sock_server.php','http://127.0.0.1/test/sock_server.php','http://127.0.0.1/test/sock_server.php','http://127.0.0.1/test/sock_server.php','http://127.0.0.1/test/sock_server.php');
//$returnedDocs = getMultipleDocuments($nodes, null);

function mkdirs($dir_path, $rights=0777){
   $dirs = explode('/', $dir_path);
   $dir='';
   foreach ($dirs as $part) {
       $dir .= $part.'/';
       if (!is_dir($dir) && strlen($dir)>0){
           mkdir($dir, $rights);
       }
   }
}